﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Diagnostics;
using Lon.Util;
using Lon.Data;

namespace Lon.Server
{
   
    public class StandByServer : FrontServerNode
    {
        private String ipAddr;
        private int port;
      
        public StandByServer( AppServer frontSever,String ipAddr,int port)
            : base(null, frontSever)
        {
            this.ipAddr = ipAddr;
            this.port = port;
 
        }
        protected override void DealDataFrame(DataFrame df)
        {
            if (df.DataFrameFlag == DataFrameFlag.Heartbeat)
            {
                lastHeartbeatTime = DateTime.Now;
                return;
            }
            else if (df.DataFrameFlag == DataFrameFlag.Data)
            {  
                if (df.DstId == this.AppServer.InterfaceId)
                {

                    List<FrontServerNode> clientArr = new List<FrontServerNode>(500);
                    lock (this.AppServer.clientDbmDict)
                    {
                        clientArr.AddRange(this.AppServer.clientDbmDict.Values);
                    }
                    for (int i = 0; i < clientArr.Count; i++)
                    {
                        clientArr[i].SendMessage(df);
                    }    
                }
                else
                {
                
                    SendToDstId(df);
                }
            }
        }
        protected override void SendToDstId(DataFrame df)
        {
            FrontServerNode sc = null;
            lock (this.AppServer.clientDbmDict)
            {
                if (!this.AppServer.clientDbmDict.ContainsKey(df.DstId))return;
                sc = this.AppServer.clientDbmDict[df.DstId];
            }
            if (sc == null) return;
            sc.SendMessage(df);
        }
        public override void Start()
        {
            Thread reConnectThread = new Thread(new ThreadStart(ConnectThread));
            reConnectThread.IsBackground = true;
            reConnectThread.Start();

        }
        private void ConnectThread()
        {
            if (String.IsNullOrEmpty(ipAddr))
            {
                RunAsSever();
            }
            else
            {
                RunAsClient();
            }
        }

        private void RunAsSever()
        {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            s.Bind(new IPEndPoint(IPAddress.Any, port));
            while (true)
            {
                s.Listen(1);
               Socket cs= s.Accept();
               this.clientSocket=cs;
               RxProc(null);
            }
        }

        private void RunAsClient()
        {
            this.clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ipAddr), port);
            while(true)
            {
                this.clientSocket.Connect(ep);
                RxProc(null);
            }
        }

     

        #region IRawDataProvider 成员
        public override string ToString()
        {
            return Name;
        }

        public override string Name
        {

            get
            {
                if (this.ClientSocket != null)
                {
                    IPEndPoint ipep = (IPEndPoint)this.ClientSocket.RemoteEndPoint;
                    return String.Format("[{0}] {1}{2}", new object[] { "热备服务器", ipep.Address, ipep.Port });
                }
                else
                {
                    return "热备服务器";
                }
            }
        }

        public string NameDesp
        {
            get
            {
                return Name;
            }
        }
   

        public int MaxCount
        {
            get
            {
                return 198;
            }
            set
            {

            }
        }

   
     

        #endregion
    }
}
